package com.real8.romemp.client.activity;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.real8.romemp.client.ClientFactory;
import com.real8.romemp.client.place.EndTurnPlace;
import com.real8.romemp.client.place.LabourAllocationPlace;
import com.real8.romemp.client.ui.EndTurnView;
import com.real8.romemp.client.ui.EndTurnView.Presenter;
import com.real8.romemp.shared.GameData;

public class EndTurnActivity extends AbstractActivity implements Presenter {
	private final ClientFactory clientFactory;
	private EndTurnView view;

	public EndTurnActivity(EndTurnPlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view = clientFactory.getEndTurnView();
		if (view != null) {
			view.setPresenter(this);

			// prepare view
			view.hideAll();

			// update gamedata for end turn
			GameData gameData = clientFactory.getGameData();
			gameData
					.setPO_population((int) (gameData.getPO_population() * 1.07));
			gameData.setFR_foodNeed(gameData.getPO_population() / 1000);
			gameData.setMA_auxiliaAvailable(gameData.getMA_auxiliaAvailable()
					+ Random.nextInt(6) + 1);
			gameData.setTN_year(gameData.getTN_year() + 1);
			gameData.setUL_freeLabour(gameData.getPO_population() / 2500);
			gameData.setShipBuildersEnrolled(false);

			// show score
			view.showScore(gameData.getSC_score());

			// show continue
			view.showContinue();

			// set widget
			containerWidget.setWidget(view.asWidget());
		}
	}

	@Override
	public void onContinue() {
		// check game end
		GameData gameData = clientFactory.getGameData();
		if (gameData.getTN_year() > -36) {
			// end of game
			view.hideAll();
			view.showGameEnd(gameData.getSC_score());
		} else {
			// next turn
			clientFactory.getPlaceController()
					.goTo(new LabourAllocationPlace());
		}
	}
}
